package org.lboot.flow.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.core.exception.BusinessException;
import org.lboot.flow.module.event.FlowCustomEvent;
import org.lboot.flow.module.event.FlowCustomEventService;
import org.lboot.flow.module.event.sp.FlowEventServiceProvider;
import org.lboot.flow.module.event.sp.FlowEventServiceProviderService;
import org.lboot.flow.module.event.sp.params.FlowEventServiceProviderCreateParams;
import org.lboot.flow.module.event.sp.params.FlowEventServiceProviderQueryParams;
import org.lboot.flow.module.event.sp.params.FlowEventServiceProviderUpdateParams;
import org.lboot.flow.module.event.sp.params.ServiceProviderRegisterParams;
import org.lboot.jpa.utils.JpaDataUtil;
import org.lboot.starter.plugin.rsr.RsrTree;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("flow/event")
@Api(tags = "服务实现")
@RsrTree("流程引擎")
@AllArgsConstructor
public class FlowCustomEventServiceController {

    FlowCustomEventService eventService;


    FlowEventServiceProviderService providerService;

    @PostMapping("services")
    @ApiOperation(value = "服务新增")
//    @CheckRole(orPerm = "flow:service:create")
    public ResponseDTO<Object> serviceCreate(@Validated @RequestBody FlowEventServiceProviderCreateParams params){
        // 查询对应的事件是否存在
        String eventId = params.getEventId();
        List<FlowCustomEvent> events = eventService.getByEventId(eventId);
        if (events.isEmpty()){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"对应事件不存在");
        }
        // 查询是否存在重复
        String serviceId = params.getServiceId();
        List<FlowEventServiceProvider> providers = providerService.getByServiceId(serviceId);
        if (!providers.isEmpty()){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"存在重复服务实现");
        }
        // 新建
        FlowEventServiceProvider provider = new FlowEventServiceProvider();
        BeanUtil.copyProperties(params, provider, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // 写入数据
        return ResponseDTO.succData(
                providerService.saveOne(provider)
        );
    }

    @PostMapping("services/register")
    @ApiOperation(value = "服务注册",notes = "具有时效性,心跳机制维持")
    public ResponseDTO<Object> serviceRegister(@Validated @RequestBody ServiceProviderRegisterParams params){
        // 获取事件ID
        String eventId = params.getEventId();

        return null;
    }

    @DeleteMapping("services/{id}")
    @ApiOperation(value = "服务删除")
//     @CheckRole(orPerm = "flow:event:delete")
    public ResponseDTO<Object> serviceDelete(@PathVariable("id") Long id){
        providerService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

    @PutMapping("services")
    @ApiOperation(value = "服务更新")
    // @CheckRole(orPerm = "flow:event:update")
    public ResponseDTO<Object> serviceUpdate(@Validated @RequestBody FlowEventServiceProviderUpdateParams params){
        Long id = params.getId();
        FlowEventServiceProvider provider = providerService.getOneUnwrap(id);
        BeanUtil.copyProperties(params, provider, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // 更新内容
        return ResponseDTO.succData(
                providerService.updateOne(provider)
        );
    }

    @GetMapping("services")
    @ApiOperation(value = "服务列表")
    public ResponseDTO<Object> serviceQueryList(FlowEventServiceProviderQueryParams params){
        Pageable pageable = JpaDataUtil.buildPageable(params);
        // 构建谓词查询
        Specification<FlowEventServiceProvider> spec = (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (Validator.isNotEmpty(params.getPriority())){
                Predicate p3 = cb.equal(root.get("priority").as(Integer.class),   params.getPriority());
                list.add(p3);
            }

            if (Validator.isNotEmpty(params.getEventId())){
                Predicate p4 = cb.equal(root.get("eventId").as(String.class),   params.getEventId());
                list.add(p4);
            }
            Predicate[] predicates = new Predicate[list.size()];
            return cb.and(list.toArray(predicates));
        };
        if (Validator.isEmpty(spec)){
            return ResponseDTO.succData(providerService.getAll(pageable));
        }
        return ResponseDTO.succData(
                providerService.getAll(pageable,spec)
        );
    }

    @GetMapping("services/{id}")
    @ApiOperation(value = "服务查询")
    public ResponseDTO<Object> serviceQuery(@PathVariable("id") Long id){
        return ResponseDTO.succData(providerService.getOneUnwrap(id));
    }

    @GetMapping("services/{id}/event")
    @ApiOperation(value = "服务关联事件查询")
    public ResponseDTO<Object> serviceEventQuery(@PathVariable("id") Long id){
        FlowEventServiceProvider provider = providerService.getOneUnwrap(id);
        // 获取事件ID
        String eventId = provider.getEventId();
        // 获取事件信息
        List<FlowCustomEvent> events = eventService.getByEventId(eventId);
        if (events.isEmpty()){
            return ResponseDTO.succData(null);
        }
        return ResponseDTO.succData(events.get(0));
    }

}
